#! /usr/bin/env node

var fs = require('fs'),
	url = require('url'),
	http = require('http'),
	path = require('path'),
	mime = require('mime'),
	api = require('./api.js');

var port = 8000,
	www = path.join(__dirname, 'www'),
	index = 'index.html';

var httpServer = http.createServer( function(request, response) {
	var redirect = false;
	var pathname = url.parse(request.url).pathname;
	
	if (pathname === '/@api') {
		api.handler(request, response);
	} else {
		var filename = path.join(www, '.', pathname);
		
		try {
			if (fs.statSync(filename).isDirectory()) {
				if (pathname[pathname.length-1] != '/') {
					response.writeHead(302, {'Location': pathname + '/'});
					response.end();
					return;
				}
				filename = path.join(filename, index);
			}
			fs.statSync(filename).isFile();
		} catch (e) {
			response.writeHead(404, {'Content-Type': 'text/plain'});
			response.write('404 Not Found');
			response.end();
			return;
		}

		response.writeHead(200, {'Content-Type': mime.lookup(filename)});
		fs.createReadStream(filename, {
			'flags': 'r',
			'encoding': 'binary',
			'mode': 0666,
			'bufferSize': 4 * 1024
		}).addListener('data', function(chunk) {
			response.write(chunk, 'binary');
		}).addListener('close', function() {
			response.end();
		});
	}
});

httpServer.listen(port);
console.log('- Listen on port ' + port);